package com.cqs.leetcode;

/**
 * Author:li
 * <p>
 * create date: 18-6-4 19:46
 */
public class SwapNodesInPairs24 {

    public ListNode swapPairs(ListNode head) {
        if (head != null && head.next != null) {
            int count = 0;
            ListNode pre = null, cur = head, next;
            //生成新的链表首部: 一定要置于cur = head之后
            head = head.next;
            while (cur != null) {
                next = cur.next;
                if (++count % 2 == 1) {
                    if (pre != null) {//第奇数个元素
                        //若所有元素为奇数个那么前两个节点指向当前节点
                        //若所有元素为偶数个那么前两个节点指向当前节点后继节点
                        pre.next.next = next == null ? cur : next;
                    }
                    //此时当前节点没有后继节点
                    cur.next = null;
                } else {
                    //偶数次 直接指向前一个元素
                    cur.next = pre;
                }
                pre = cur;
                cur = next;
            }
        }
        return head;
    }

    public static void main(String[] args) {
        int[] nums = new int[2];
        for (int i = 0; i < nums.length; i++) {
            nums[i] = i + 1;
        }
        ListNode head = ListNode.build(nums);
        System.out.println(head);
        SwapNodesInPairs24 swap = new SwapNodesInPairs24();
        System.out.println(swap.swapPairs(head));
    }
}
